<!-- 商品入库 -->
<template>
  <div>
    <el-card style="max-width: 100%;">
      <search-box :tableDataInput="tableData" @search="handleSearch"></search-box>
      <el-button class="btn2">导入</el-button>
      <el-button class="btn1" @click="showaddDialog"><i class="el-icon-plus"
          style="margin-right: 3px;"></i>入库单</el-button>
      <el-table :data="selectedItems" style="font-size: 16px;position: relative;top:-20px;"
        :header-cell-style="{ background: '#EBEEF2' }" :row-style="{ height: '80px' }">
        <el-table-column prop="stockSn" label="入库单编号" :show-overflow-tooltip="true" align="center" />
        <el-table-column prop="commodityName" label="商品名称" align="center">
          <template slot-scope="scope">
            <span @click="opendetails(scope.row)">{{ scope.row.commodityName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="spData" label="规格及参数" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div>
              <span v-for="(attr, index) in formatAttributes(scope.row.spData)" :key="index">
                {{ attr }}
                <span v-if="index < formatAttributes(scope.row.spData).length - 1">，</span>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="price" label="单价" align="center" />
        <el-table-column prop="stockNumber" label="数量" align="center" />
        <el-table-column prop="money" label="金额" align="center" />
        <el-table-column prop="createTime" label="创建日期" align="center" />
        <el-table-column prop="createByName" label="创建人" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <div v-if="scope.row.status == 1">已确认</div>
            <div v-else style="color: red;">待确认</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250%">
          <template slot-scope="scope">
            <div v-if="scope.row.status != 1">
              <span @click="confirm(scope.$index, scope.row)">
                <img src="../../assets/confirm.svg" class="confirm">
                确认
              </span>
              <span @click="edit(scope.row)">
                <img src="../../assets/edit.svg" class="edit">
                编辑
              </span>
              <span @click="deleted(scope.$index, scope.row)">
                <img src="../../assets/delete.svg" class="delete">
                删除
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 入库单的弹窗 -->
      <AddInboundOrder :dialogVisible.sync="addDialogvisible" @reloadData="handleReloadData" />
    </el-card>

    <el-pagination background layout="->,prev, pager,next,total" :page-size="10" :total="tableDataLength"
      @current-change="handleCurrentChange" style="margin-top: 20px;">
    </el-pagination>

    <EditStockDialog :visible.sync="editDialogVisible" :rowData="currentRowData" @submit="updateStock" />
    <ShowInboundOrder :visible.sync="showDetailsDialogVisible" :rowData="currentRowData"/>
  </div>
</template>

<script>
import { getAllStocks, deleteStock, updateStockStatus, updateStock, getSkuList } from '@/api/api.js';
import AddInboundOrder from './components/AddInboundOrder.vue';
import EditStockDialog from './components/EditStockDialog.vue';
import ShowInboundOrder from './components/ShowInboundOrder.vue'
export default {
  components: {
    AddInboundOrder,
    EditStockDialog,
    ShowInboundOrder
  },
  data() {
    return {
      selectedItems: [],
      tableData: [],
      tableDataLength: 0,
      currentpageNumber: 0,
      input3: '',
      input: '',
      addDialogvisible: false,
      editDialogVisible: false,
      showDetailsDialogVisible: false,
      currentRowData: {},
      skuCode : '',
      tags: [
        { name: '华为Pura70 Ultra', type: '' },
      ],
      stockdeatil: { // 请求参数
        name: '',
        pageNo: 1,
      },
    };
  },
  async created() {
    await this.getAllStocks(this.stockdeatil);
    this.currentpageNumber = 1;
  },
  methods: {
    async getAllStocks(data) {
      try {
        const res = await getAllStocks(data);
        if (res.data.code == 200) {
          this.selectedItems = res.data.result.records;
          this.tableData = res.data.result.records;
          this.tableDataLength = res.data.result.total;
        }
      } catch (error) {
        console.log(error);
      }
    },
    formatAttributes(attributes) {
      let parsedAttributes = [];
      try {
        parsedAttributes = JSON.parse(attributes);
      } catch (e) {
        console.error('Error parsing attributes:', e);
      }

      if (Array.isArray(parsedAttributes)) {
        return parsedAttributes.map(attr => `${attr.key}：${attr.value}`);
      } else {
        return [];
      }
    },
    handleCurrentChange(val) {
      this.stockdeatil.pageNo = val;
      this.getAllStocks(this.stockdeatil);
      this.currentpageNumber = val;
    },
    handleSearch(name) {
      this.stockdeatil.name = name;
      this.getAllStocks(this.stockdeatil);
      this.currentpageNumber = 1;
    },
    showaddDialog() {
      this.addDialogvisible = true;
    },
    opendetails(row){
      this.currentRowData = row;
      this.showDetailsDialogVisible = true;
    },
    confirm(index, row) {
      this.$confirm('是否确认入库?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateStockStatus(row.stockDetailId).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '确认成功!'
            });
            row.status = 1;
          }
        });
      }).catch(() => { });
    },
    edit(row) {
      this.currentRowData = row;
      this.editDialogVisible = true;
    },
    deleted(index, row) {
      this.$confirm('此操作将永久删除该条入库记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStock(row.stockDetailId).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.stockdeatil.pageNo = this.currentpageNumber;
            this.getAllStocks(this.stockdeatil); // 等价于刷新列表
          }
        });
      }).catch(() => { });
    },
    handleReloadData() {
      // 调用 getAllStocks 方法
      this.stockdeatil.pageNo = this.currentpageNumber;
      this.getAllStocks(this.stockdeatil);
    },
    async updateStock(formData) {
      const productSku = await getSkuList(formData.commodityId)
      if (Array.isArray(productSku.data.result)) {
        productSku.data.result.forEach((sku) => {
          this.skuCode= sku.skuCode;
        });
      } else {
        console.error('Invalid productSku data:', productSku.data.result);
      }
      // // 构造后端期望的表单数据格式
      const formattedData = {
        commodityId: formData.commodityId,
        editSkuDTOList: [
          {
            id: formData.stockDetailId,
            money: Number(formData.money),
            price: Number(formData.price),
            skuCode: this.skuCode,
            stockNumber: Number(formData.stockNumber),
            unit: formData.unit
          }
        ],
        id: formData.stockDetailId,
        remark: formData.remark,
        stockSn: formData.stockSn
      };
        try {
          const res = await updateStock(formattedData);
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '更新成功!'
            });
            this.getAllStocks(this.stockdeatil); // 刷新列表
          }
        } catch (error) {
          console.error('Error updating stock:', error);
        }
    },
  }
};
</script>

<style scoped>
.input1 {
  font-size: 16px;
  width: 241px;
  opacity: 1;
  border-radius: 80px;
  background: rgb(153, 155, 158);
}

.input1>>>input.el-input__inner {
  background: rgba(235, 238, 242, 1);
  border-radius: 20px;
}

.btn1 {
  position: relative;
  float: right;
  top:-40px;
  right: 10px;
  opacity: 1;
  border-radius: 80px;
  width: 130px;
  height: 38px;
  color: white;
  font-size: 15px;
  background: rgba(126, 114, 242, 1);
}

.btn2 {
  position: relative;
  float: right;
  text-align: center;
  top:-40px;
  opacity: 1;
  border-radius: 80px;
  width: 130px;
  height: 38px;
  line-height: 15px;
  color: white;
  font-size: 15px;
  background: rgba(126, 114, 242, 1);
}

.confirm {
  width: 13.2px;
  height: 14px;
  margin-right: 4px;
}

.edit {
  width: 13.2px;
  height: 14px;
  margin-left: 30px;
  margin-right: 4px;
}

.delete {
  width: 13.2px;
  margin-left: 30px;
  margin-right: 4px;
}


.el-pagination {
  float: right;
}

.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-icon-search {
  margin-top: 14px;
  /* margin-left: 15px;
      margin-right: 15px; */
  width: 15px;
  margin-left: 6px;
}
</style>